package com.iona.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.iona.json.JSONException;
import com.iona.utils.HibernateUtils;

public abstract class BaseServlet extends HttpServlet {

	private static final long serialVersionUID = 7544115056471173110L;

	private boolean transactional;

	public boolean isTransactional() {
		return transactional;
	}

	public void setTransactional(boolean transactional) {
		this.transactional = transactional;
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		execute(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		execute(request, response);
	}

	private void execute(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			if (isTransactional()) {
				HibernateUtils.getSessionFactory().getCurrentSession()
						.beginTransaction();
			}
			doExecute(request, response);

			if (isTransactional()) {
				HibernateUtils.getSessionFactory().getCurrentSession()
						.getTransaction().commit();
			}
		} catch (Exception ex) {
			if (HibernateUtils.getSessionFactory().getCurrentSession()
					.getTransaction().isActive()) {
				HibernateUtils.getSessionFactory().getCurrentSession()
						.getTransaction().rollback();
			}
			if (ServletException.class.isInstance(ex)) {
				throw (ServletException) ex;
			} else {
				throw new ServletException(ex);
			}
		}
	}

	protected void goToList(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		getServletConfig().getServletContext()
				.getRequestDispatcher("/index.jsp").forward(request, response);
	}

	public abstract void doExecute(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException,
			JSONException;

}
